package com.dream.prm.common;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 端口工具
 * 
 * @author w.g
 * @date 2019-07-18
 * 
 */
@SuppressWarnings("all")
public class PortUtils {
	
	/**
	 * 查看端口是否被占用
	 * T/F: 占用/空闲
	 * @param port
	 * @return
	 */
	public static boolean isPortAvailable(int port) {
		Socket s = new Socket();
		boolean flag = false;
		String f = "";
		List<String> ipList = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface nif = netInterfaces.nextElement();
				Enumeration<InetAddress> iparray = nif.getInetAddresses();
				while (iparray.hasMoreElements()) {
					ipList.add(iparray.nextElement().getHostAddress());
				}
			}

			for (int i = 0; i < ipList.size(); i++) {
				flag = bindPort(ipList.get(i), port);
				if (flag) {
					break;
				}
			}

			if (flag) {// 已被占用
				return true;
			} else {// 未被占用
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	/**
	* 测试主机Host的port端口是否被使用
	* T/F: 占用/空闲
	* @param host
	* @param port
	* @return
	* @throws Exception
	*/
	public static Boolean bindPort(String host, int port) throws Exception {
		boolean flag=false;
		try {
			//该主机的特定端口号能建立一个socket,则说明该主机的该端口正在使用
			Socket s = new Socket(InetAddress.getByName(host),port); 
			s.close();
			flag=true;
		} catch (Exception e) {
			flag=false;
			//e.printStackTrace();
		} finally{
			return flag;
		}
	}
	
	
	
	public static void main(String[] args) {
		try {
			//System.out.println(isPortAvailable(9080));
			System.out.println(bindPort("192.168.2.223",9080));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
	
	
}
